/**
 * Copyright 2020 OPSLI 快速开发平台 https://www.opsli.com
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.opsli.modulars.customer.record.web;

import cn.hutool.core.convert.Convert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.opsli.api.base.result.ResultWrapper;
import org.opsli.api.web.customer.record.CustomerRecordRestApi;
import org.opsli.api.wrapper.customer.customerrelation.CustomerStudentRelationModel;
import org.opsli.api.wrapper.customer.record.CustomerRecordModel;
import org.opsli.api.wrapper.system.user.UserModel;
import org.opsli.common.annotation.ApiRestController;
import org.opsli.core.base.controller.BaseRestController;
import org.opsli.core.log.annotation.OperateLogger;
import org.opsli.core.log.enums.ModuleEnum;
import org.opsli.core.log.enums.OperationTypeEnum;
import org.opsli.core.persistence.Page;
import org.opsli.core.persistence.querybuilder.QueryBuilder;
import org.opsli.core.persistence.querybuilder.WebQueryBuilder;
import org.opsli.core.utils.UserUtil;
import org.opsli.modulars.customer.record.entity.CustomerRecord;
import org.opsli.modulars.customer.record.service.ICustomerRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.Transient;
import java.util.Date;
import java.util.Optional;

/**
 * CustomerRecord Controller
 *
 * @author guagua
 * @date 2025-06-12 13:51:39
 */
@Api(tags = CustomerRecordRestApi.TITLE)
@Slf4j
@ApiRestController("/{ver}/customer/Record")
public class CustomerRecordRestController
        extends BaseRestController<CustomerRecord, CustomerRecordModel, ICustomerRecordService>
        implements CustomerRecordRestApi {

    @Autowired
    private org.opsli.modulars.customer.customerrelation.service.CustomerBusinessService customerBusinessService;

    @Autowired
    private org.opsli.modulars.customer.record.service.CustomerRecordBusinessService customerRecordBusinessService;

    /**
     * CustomerRecord 查一条
     *
     * @param model 模型
     * @return ResultWrapper
     */
    @ApiOperation(value = "获得单条CustomerRecord", notes = "获得单条CustomerRecord - ID")
    @PreAuthorize("hasAuthority('customer_record_select')")
    @Override
    public ResultWrapper<CustomerRecordModel> get(CustomerRecordModel model) {
        // 如果系统内部调用 则直接查数据库
        if (model != null && model.getIzApi() != null && model.getIzApi()) {
            model = IService.get(model);
        }
        return ResultWrapper.getSuccessResultWrapper(model);
    }

    /**
     * CustomerRecord 查询分页
     *
     * @param pageNo   当前页
     * @param pageSize 每页条数
     * @param request  request
     * @return ResultWrapper
     */
    @ApiOperation(value = "获得分页数据", notes = "获得分页数据 - 查询构造器")
    @PreAuthorize("hasAuthority('customer_record_select')")
    @Override
    public ResultWrapper<?> findPage(Integer pageNo, Integer pageSize, HttpServletRequest request) {

        QueryBuilder<CustomerRecord> queryBuilder = new WebQueryBuilder<>(IService.getEntityClass(),
                request.getParameterMap());
        Page<CustomerRecord, CustomerRecordModel> page = new Page<>(pageNo, pageSize);
        page.setQueryWrapper(queryBuilder.build());
        page = IService.findPage(page);

        return ResultWrapper.getSuccessResultWrapper(page.getPageData());
    }

    /**
     * CustomerRecord 新增
     *
     * @param model 模型
     * @return ResultWrapper
     */
    @Transient
    @ApiOperation(value = "新增CustomerRecord数据", notes = "新增CustomerRecord数据")
    @PreAuthorize("hasAuthority('customer_record_insert')")
    @OperateLogger(description = "新增CustomerRecord数据", module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.INSERT, db = true)
    @Override
    public ResultWrapper<?> insert(CustomerRecordModel model) {

        // 判断客户是否存在
        if (!customerBusinessService.validateCustomerExists(model.getCustomerId())) {
            return ResultWrapper.getCustomResultWrapper(500, "客户不存在");
        }
        // 调用新增方法
        IService.insert(model);
        // 判断是否需要提醒
        if (model.getAssignedTo() != null && model.getReminderTime() != null) {
            // 调用提醒方法
            reminder(model);
        }
        return ResultWrapper.getSuccessResultWrapperByMsg("新增记录成功");
    }

    /**
     * 提醒
     *
     * @param model 模型
     */
    private void reminder(CustomerRecordModel model) {
        // 获取提醒人
        String assignedTo = model.getAssignedTo();
        UserModel user = UserUtil.getUser(assignedTo);
        if (user == null) {
            throw new RuntimeException("Reminder user does not exist");
        }
        // 获取提醒人邮件
        String email = user.getEmail();
        if (email == null) {
            throw new RuntimeException("Reminder user email does not exist");
        }

        // 获取提醒时间
        Date reminderTime = model.getReminderTime();
        if (reminderTime == null) {
            throw new RuntimeException("Reminder time cannot be empty");
        }

        // 获取提醒内容
        String reminderContent = model.getDescription();
        if (reminderContent == null) {
            reminderContent = "You have a new reminder";
        }

        // 添加提醒任务
        IService.addReminder(user.getId(), reminderTime, email, reminderContent);
    }

    /**
     * CustomerRecord 修改
     *
     * @param model 模型
     * @return ResultWrapper
     */
    @ApiOperation(value = "修改CustomerRecord数据", notes = "修改CustomerRecord数据")
    @PreAuthorize("hasAuthority('customer_record_update')")
    @OperateLogger(description = "修改CustomerRecord数据", module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.UPDATE, db = true)
    @Override
    public ResultWrapper<?> update(CustomerRecordModel model) {
        // 调用修改方法
        IService.update(model);
        return ResultWrapper.getSuccessResultWrapperByMsg("修改CustomerRecord成功");
    }

    /**
     * CustomerRecord 删除
     *
     * @param id ID
     * @return ResultVo
     */
    @ApiOperation(value = "删除CustomerRecord数据", notes = "删除CustomerRecord数据")
    @PreAuthorize("hasAuthority('customer_record_delete')")
    @OperateLogger(description = "删除CustomerRecord数据", module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.DELETE, db = true)
    @Override
    public ResultWrapper<?> del(String id) {
        IService.delete(id);
        return ResultWrapper.getSuccessResultWrapperByMsg("删除CustomerRecord成功");
    }

    /**
     * CustomerRecord 批量删除
     *
     * @param ids ID 数组
     * @return ResultVo
     */
    @ApiOperation(value = "批量删除CustomerRecord数据", notes = "批量删除CustomerRecord数据")
    @PreAuthorize("hasAuthority('customer_record_delete')")
    @OperateLogger(description = "批量删除CustomerRecord数据", module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.DELETE, db = true)
    @Override
    public ResultWrapper<?> delAll(String ids) {
        String[] idArray = Convert.toStrArray(ids);
        IService.deleteAll(idArray);
        return ResultWrapper.getSuccessResultWrapperByMsg("批量删除CustomerRecord成功");
    }

    /**
     * CustomerRecord Excel 导出认证
     *
     * @param type    类型
     * @param request request
     */
    @ApiOperation(value = "Excel 导出认证", notes = "Excel 导出认证")
    @PreAuthorize("hasAnyAuthority('customer_record_export', 'customer_record_import')")
    @Override
    public ResultWrapper<String> exportExcelAuth(String type, HttpServletRequest request) {
        Optional<String> certificateOptional = super.excelExportAuth(type, CustomerRecordRestApi.SUB_TITLE, request);
        if (!certificateOptional.isPresent()) {
            return ResultWrapper.getErrorResultWrapper();
        }
        return ResultWrapper.getSuccessResultWrapper(certificateOptional.get());
    }

    /**
     * CustomerRecord Excel 导出
     *
     * @param response response
     */
    @ApiOperation(value = "导出Excel", notes = "导出Excel")
    @PreAuthorize("hasAuthority('customer_record_export')")
    @OperateLogger(description = "CustomerRecord 导出Excel", module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.SELECT, db = true)
    @Override
    public void exportExcel(String certificate, HttpServletResponse response) {
        // 导出Excel
        super.excelExport(certificate, response);
    }

    /**
     * CustomerRecord Excel 导入
     *
     * @param request 文件流 request
     * @return ResultVo
     */
    @ApiOperation(value = "导入Excel", notes = "导入Excel")
    @PreAuthorize("hasAuthority('customer_record_import')")
    @OperateLogger(description = "CustomerRecord Excel 导入", module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.INSERT, db = true)
    @Override
    public ResultWrapper<?> importExcel(MultipartHttpServletRequest request) {
        return super.importExcel(request);
    }

    // ========================================
    // 客户操作记录相关方法
    // ========================================

    /**
     * 新增客户时创建记录
     *
     * @param customerData 客户数据
     * @return ResultWrapper
     */
    @ApiOperation(value = "新增客户操作记录", notes = "当新增客户时自动创建操作记录")
    @PreAuthorize("hasAuthority('customer_record_insert')")
    @PostMapping("/createCustomerAddRecord")
    public ResultWrapper<?> createCustomerAddRecord(
            CustomerStudentRelationModel customerData) {
        try {
            boolean result = customerRecordBusinessService.createCustomerAddRecord(
                    customerData.getId());
            if (result) {
                return ResultWrapper.getSuccessResultWrapperByMsg("新增客户记录创建成功");
            } else {
                return ResultWrapper.getErrorResultWrapper().setMsg("新增客户记录创建失败");
            }
        } catch (Exception e) {
            log.error("创建新增客户记录失败", e);
            return ResultWrapper.getErrorResultWrapper().setMsg("创建新增客户记录失败: " + e.getMessage());
        }
    }

    /**
     * 修改客户时创建记录（比较新旧数据）
     *
     * @param customerId 客户ID
     * @param oldData    修改前数据
     * @param newData    修改后数据
     * @return ResultWrapper
     */
    @ApiOperation(value = "修改客户操作记录", notes = "当修改客户时自动创建操作记录，记录变更内容")
    @PreAuthorize("hasAuthority('customer_record_insert')")
    @PostMapping("/createCustomerUpdateRecord")
    public ResultWrapper<?> createCustomerUpdateRecord(
            @RequestParam("customerId") String customerId,
            @RequestParam("oldData") Object oldData,
            @RequestParam("newData") Object newData) {
        try {
            boolean result = customerRecordBusinessService.createCustomerUpdateRecord(customerId, oldData, newData);
            if (result) {
                return ResultWrapper.getSuccessResultWrapperByMsg("修改客户记录创建成功");
            } else {
                return ResultWrapper.getErrorResultWrapper().setMsg("修改客户记录创建失败");
            }
        } catch (Exception e) {
            log.error("创建修改客户记录失败", e);
            return ResultWrapper.getErrorResultWrapper().setMsg("创建修改客户记录失败: " + e.getMessage());
        }
    }

    /**
     * 修改客户状态时创建记录
     *
     * @param customerId 客户ID
     * @param oldStatus  原状态
     * @param newStatus  新状态
     * @param reason     修改原因
     * @return ResultWrapper
     */
    @ApiOperation(value = "客户状态变更记录", notes = "当客户状态发生变更时自动创建记录")
    @PreAuthorize("hasAuthority('customer_record_insert')")
    @PostMapping("/createCustomerStatusChangeRecord")
    public ResultWrapper<?> createCustomerStatusChangeRecord(
            @RequestParam("customerId") String customerId,
            @RequestParam("oldStatus") String oldStatus,
            @RequestParam("newStatus") String newStatus,
            @RequestParam(value = "reason", required = false) String reason) {
        try {
            boolean result = customerRecordBusinessService.createCustomerStatusChangeRecord(customerId, oldStatus,
                    newStatus, reason);
            if (result) {
                return ResultWrapper.getSuccessResultWrapperByMsg("状态变更记录创建成功");
            } else {
                return ResultWrapper.getErrorResultWrapper().setMsg("状态变更记录创建失败");
            }
        } catch (Exception e) {
            log.error("创建状态变更记录失败", e);
            return ResultWrapper.getErrorResultWrapper().setMsg("创建状态变更记录失败: " + e.getMessage());
        }
    }

}